
//反链 
class XrlParser {
  int index=0;
  String content="";
  Map<String,dynamic> tree={};

  XrlParser(Iterable<String> keys){
    keys.forEach(addkey);  
  }
  void addkey(String s) {
    var p = tree;
		for(int i=0;i<s.length;i++){
      var c = s[i];
      if(!p.containsKey(c)) {
        p[c] =  <String, dynamic>{};
      }
			p = p[c];
		}
		p['']=s;
  }
  String nextWord() {
    String rt = "";
    index++;
    while(index<content.length && !RegExp(r'\s').hasMatch( content[index])) {
      rt+=content[index++];
    }
    index--;
    return rt;
  }
  void parse(String text, Null Function(String text) onFindOne) {
      content = text.trim();
      var rtc="";
      for(index=0;index<content.length;index++){
        var c = content[index];
        rtc+=c;
        //换行就返回数据
        if(c=="\n"){
          onFindOne(rtc); 
          // //过滤掉的换行符后的空白
          // final match = RegExp(r'^\s+').firstMatch(content.substring(index+1));
          // index+=match?.group(0)?.length ?? 0;
          rtc="";
          continue;
        }
        //获取到单词就返回数据 
        var a = cget(c);
        if(a.isNotEmpty){
          if(rtc.length>a[0].length){ 
            onFindOne(rtc.substring(0,rtc.length-a[0].length));
          }
          rtc="";
          onFindOne(a[0]);
          continue;
        }
      }
      onFindOne("$rtc\n");
  }

  static List<dynamic> tlist=[];  // 静态 存放当前启动的线程
  List<String> cget(c){  
    List<String> tok = [];	//匹配成功的关键
    if(tree[c]!=null ) tlist.add(tree);
    var count=tlist.length;
    for(int i=0;i<count;i++){
      tlist[i]= tlist[i][c];
      if(tlist[i]!=null && tlist[i]['']!=null) tok.add(tlist[i]['']);	// 如果关键字匹配成功 保存关键字到tok数组
    }
    tlist.removeWhere((v){return v==null;});

    //$e_time3 = microtime(true)*1000;
    //echo "All use $count time ".($e_time3 - $s_time3)." seconds.\n"; 
    return tok;
  }


}